package com.sunday.common.mybatis.plus.study.e3_Enums;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.sunday.common.leaf.config.LeafProperties;
import com.sunday.common.leaf.core.IdWorker;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Slf4j
@Configuration
//@MapperScan("com.sunday.common.mybatis.plus.study.tool.db")
public class MybatisPlusConfig implements EnvironmentAware {

    private Environment env;

    private Binder binder;


    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        /**
         * 分页
         */
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource, MybatisPlusProperties mybatisPlusProperties) throws Exception {
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
        // 其他相关设置
        return sessionFactoryBean.getObject();
    }

//    @Bean
//    public MybatisPlusPropertiesCustomizer mybatisPlusPropertiesCustomizer() {
//        return properties -> {
//            GlobalConfig globalConfig = properties.getGlobalConfig();
//            globalConfig.setBanner(false);
//            MybatisPlusProperties.CoreConfiguration configuration = new MybatisPlusProperties.CoreConfiguration();
//            configuration.setDefaultEnumTypeHandler(MybatisEnumTypeHandler.class);
//            properties.setConfiguration(configuration);
//        };
//    }

    @Override
    public void setEnvironment(Environment environment) {
        this.env = environment;
        binder = Binder.get(this.env);
    }

    @PostConstruct
    public void idWorker() {
        LeafProperties leafProperties = binder.bindOrCreate("sunday.leaf.snowflake", LeafProperties.class);
        IdWorker.build(leafProperties);
    }

}